<script setup lang="ts">
   
import {onMounted, reactive, ref, nextTick} from 'vue'
import { hasTrademarkAPI, addOrUpdateTrademarkAPI, DeleteTrademark } from '@/network/product/trakemark';
// 忘记写lang='ts' 不能引入 
import type { TradeMarkResponseData, Records, TradeMark } from '@/network/product/trakemark/type';
import { ElMessage, type UploadProps } from 'element-plus'
// 当前页面
const pageNO = ref(1)
 
// 每一页展示数据条数
const limit = ref(3)
const total = ref<number>(0)
// 已有品牌数据
const trademarkArr = ref<Records>([])
async function getHasTrademark(pager = 1) {
  pageNO.value = pager
   const res: TradeMarkResponseData = await hasTrademarkAPI(pageNO.value, limit.value)
  //  console.log(res);
   if (res.code === 200) {
    total.value = res.data.total
    trademarkArr.value = res.data.records
   }
   
}

onMounted(() => {
    getHasTrademark()
})

// // 分页器页码变化，可省略，直接在模板上写重新获取数据方法
// function changePage(a:number) {
//   getHasTrademark()
// }

function sizeChange() {
  pageNO.value = 1
  getHasTrademark()
}

// 控制对话框显示与隐藏
const dialogFormVisible = ref<boolean>(false)

function addTrademark() {
  dialogFormVisible.value = true
  // 每次添加时，清空收集数据
  delete trademarkParams.id 
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
  // // 第一种方法，可选链
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  // 第二种方法
  nextTick(() => {
    formRef.value.clearValidate(['tmName', 'logoUrl'])
  })
}

// 定义收集品牌数据
const trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})

// 上传图片之前触发的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile);
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M'
      })
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式为PNG|JPG|GIF'
    })
  }
}
// 图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  // response: 即为上传服务器返回的数据
  // console.log(response);
  // 收集上传图片的地址
  trademarkParams.logoUrl = response.data
  // 图片上传成功，清除校验信息
  formRef.value.clearValidate('logoUrl')
}

// 根据是否携带id 发送不同接口，添加或修改品牌
const formRef = ref(null)
async function confirm() {
  // 全部校验通过，再去发请求
 await formRef.value.validate()

  const res = await addOrUpdateTrademarkAPI(trademarkParams)
  console.log(res);
  if (res.code === 200) {
    // 判断添加还是修改，决定停留在哪一页
    getHasTrademark(trademarkParams.id ? pageNO.value : 1)
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改成功': '添加成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改失败': '添加失败'
    })
  }
  
  dialogFormVisible.value = false
}


// 修改
// row当前的已有品牌 
function updateTrademark(row: TradeMark) {
  // nextTick中拿不到formRef 未知错误
  // 清除校验信息
  // nextTick(() => {
    // console.log(formRef.value);
    formRef.value?.clearValidate(['tmName', 'logoUrl'])
  // })
  // console.log(row);
  trademarkParams.tmName = row.tmName
  trademarkParams.logoUrl = row.logoUrl
  // 修改品牌需收集id
  trademarkParams.id = row.id
  dialogFormVisible.value = true
}

function cancel() {
  dialogFormVisible.value = false
}


// 表单校验规则对象
function validatorTmName(rule: any, value: any, callback: any) {
  console.log(value);
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名需大于2位'))
  }
}

function validatorLogoUrl(rule: any, value: any, callback: any) {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传图片'))
  }
}
const rules = {
  tmName: [
    {required: true, trigger: 'blur', validator: validatorTmName}
  ],
  logoUrl: [{required: true, trigger: 'blur', validator: validatorLogoUrl} ]
}

// 删除品牌
async function removeTrademark(id: number) {
  const res = await DeleteTrademark(id)
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功'
    })
    getHasTrademark(trademarkArr.value.length > 1 ? pageNO.value : pageNO.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败'
    })
  }

  
}

</script>


<template>
    <div class="box">
        <el-card>
            <el-button type="primary" icon="Plus" @click="addTrademark" v-has="'btn.Trademark.add'">添加品牌</el-button>
            <el-table style="margin: 10px 0;" stripe border :data="trademarkArr">
                <el-table-column type="index" label="序号" width="80" align="center" />
                <!-- table-column默认展示数据用div 可以用插槽 -->
                <el-table-column label="品牌名称" width="180" prop="tmName">

                </el-table-column>
                <el-table-column  label="品牌LOGO">
                    <template #="{row, $index}">
                         <el-image style="width: 100px; height: 100px" :src="row.logoUrl">
                            <template #error>
                                <img style="width: 100px; height: 100px;" src="https://img0.baidu.com/it/u=2007219514,3684347995&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1734714000&t=4c13c255997dad2075adfe9932b6a447" alt="">
                            </template>
                         </el-image>
                    </template>
                </el-table-column>
                <el-table-column  label="品牌操作">
                    <template #="{row, $index}">
                        <el-button v-has="'btn.Trademark.update'" type="primary" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>
                        <el-popconfirm :title="`确定要删除${row.tmName}吗`" @confirm="removeTrademark(row.id)" width="200px" icon="Delete" icon-color="red">
                          <template #reference>
                            <el-button v-has="'btn.Trademark.remove'" type="primary" size="small" icon="Delete"></el-button>
                          </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器组件
             v-model:current-page: 设置分页器当前页码
             v-model: page-size: 设置每页展示数据的条数
             page-sizes: 下拉菜单数据条数
             background: 是否为分页按钮添加背景色
             layout: -> 顶到右侧布局
              -->
            <el-pagination
            v-model:current-page="pageNO"
            v-model:page-size="limit"
            :page-sizes="[3, 5, 7, 9]"
            :background="true"
            layout=" prev, pager, next, jumper, ->, sizes, total,"
            :total="total"
            @current-change="getHasTrademark"
            @size-change="sizeChange"
            />
        </el-card>
        <!-- 对话框组件：添加品牌、修改品牌 -->
        <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌': '添加品牌'">
          <el-form ref="formRef" style="width: 80%;" :model="trademarkParams" :rules="rules">
            <el-form-item label="品牌名称" label-width="100px" prop="tmName">
              <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
            </el-form-item>
            <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
              <!-- 
               1. action上传服务器图片，得写/api 否则代理服务器不发送这次post请求
              2. show-file-list: 展示文件名
              3. before-upload: 上传文件之前，约束文件类型、大小
               -->
              <el-upload
                class="avatar-uploader"
                action="/api/admin/product/fileUpload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
          <!-- 具名插槽footer -->
           <template #footer>
            <el-button @click="cancel">取消</el-button>
            <el-button @click="confirm" type="primary">确定</el-button>
           </template>
        </el-dialog>
    </div>
</template>


<style scoped lang='scss'>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>